<template>
  <div class="work-order" @touchmove="handleTouchMove">
    <van-nav-bar title="创建新工单" left-text="返回" left-arrow @click-left="onClickLeft" />
    <div class="work-order-content">
      <van-form @submit="submit" scroll-to-error>
        <van-cell-group inset>
          <van-field v-model="form.created_by_name" label="工单创建人" readonly label-width="120px" />

          <van-field v-model="form.supervisor_name" label="负责人" readonly label-width="120px" />

          <template v-if="!cieType">
            <van-field v-model="form.customer" label="FAB" readonly label-width="120px" />
          </template>

          <template v-else>
            <van-field v-model="form.customer" is-link label="FAB" placeholder="请选择"
              :rules="[{ required: true, message: 'FAB不能为空' }]" required @click="fabShow = true" readonly
              label-width="120px" />
            <van-popup v-model:show="fabShow" destroy-on-close position="bottom">
              <van-picker :columns="fabColumns" :model-value="fabValue" :columns-field-names="customFieldName"
                @confirm="fabOnConfirm" @cancel="fabShow = false" />
            </van-popup>
          </template>

          <template v-if="!cieType">
            <van-field v-model="form.reporter_name" label="客户联系人" readonly label-width="120px" />
          </template>

          <template v-else>
            <van-field v-model="form.reporter_name" is-link label="客户联系人" placeholder="请选择"
              :rules="[{ required: true, message: '客户联系人不能为空' }]" required @click="clientShow = true" readonly
              :disabled="!form.customer" label-width="120px" />
            <van-popup v-model:show="clientShow" destroy-on-close position="bottom">
              <van-picker :columns="clientColumns" :model-value="clientValue" :columns-field-names="customFieldName"
                @confirm="clientOnConfirm" @cancel="clientShow = false" />
            </van-popup>
          </template>

          <van-field v-model="form.phone_number" label="电话" readonly label-width="120px" />

          <van-field v-model="form.email_address" label="邮箱" readonly label-width="120px" />

          <van-field v-model="form.ticket_type_name" is-link label="工单类型" placeholder="请选择"
            :rules="[{ required: true, message: '工单类型不能为空' }]" required @click="workTypeShow = true" label-width="120px"
            readonly :disabled="!form.customer">
            <template #input>
              <van-popover v-model:show="workTypeShow" :actions="workOrderActions1" v-if="form.customer"
                @select="onSelect">
                <template #reference>
                  <div style="color: #d9d9d9; font-weight: 600;" v-if="!form.ticket_type_name">
                    请选择
                  </div>

                  <div v-else>{{ form.ticket_type_name }}</div>
                </template>
              </van-popover>
            </template>
          </van-field>

          <van-field v-model="form.ticket_cate_name" is-link label="工单分类" placeholder="请选择"
            :rules="[{ required: true, message: '工单分类不能为空' }]" required @click="classifyShow = true" label-width="120px"
            readonly :disabled="form.ticket_type !== 0 && form.ticket_type !== 1">
            <template #input>
              <van-popover v-model:show="classifyShow" :actions="form.ticket_type === 0 ? issueClassify : consultationClassify
                " v-if="form.ticket_type_name" @select="classifyOnSelect">
                <template #reference>
                  <div style="color: #d9d9d9; font-weight: 600;" v-if="!form.ticket_cate_name">
                    请选择
                  </div>
                  <div v-else>{{ form.ticket_cate_name }}</div>
                </template>
              </van-popover>
            </template>
          </van-field>

          <template v-if="!form.ticket_type">
            <van-field v-model="form.device_sn_cust_name" is-link label="客户设备编号" placeholder="请选择"
              :rules="[{ required: true, message: '客户设备编号不能为空' }]" required @click="deviceNumber" readonly
              label-width="120px" :disabled="!form.customer" />
            <van-popup v-model:show="deviceNumberShow" destroy-on-close position="bottom">
              <van-picker :columns="deviceNumberColumns" :model-value="deviceNumberValue"
                :columns-field-names="customFieldName" @confirm="customFieldConfirm"
                @cancel="deviceNumberShow = false" />
            </van-popup>
          </template>

          <template v-if="!form.ticket_type">
            <van-field v-model="form.device_status_name" is-link label="设备状态" placeholder="请选择"
              :rules="[{ required: true, message: '设备状态不能为空' }]" required @click="deviceStatusShow = true"
              label-width="120px">
              <template #input>
                <van-popover v-model:show="deviceStatusShow" :actions="equipmentActions" @select="deviceSelect">
                  <template #reference>
                    <div style="color: #d9d9d9; font-weight: 600;" v-if="!form.device_status_name">
                      请选择
                    </div>
                    <div v-else>{{ form.device_status_name }}</div>
                  </template>
                </van-popover>
              </template>
            </van-field>
          </template>

          <van-field v-model="form.device_type" label="设备型号" readonly label-width="120px" v-if="!form.ticket_type" />

          <van-field v-model="form.device_sn" label="设备序列号" readonly label-width="120px" v-if="!form.ticket_type" />

          <van-field v-model="form.device_warranty" label="设备保修到期日" readonly label-width="120px"
            v-if="!form.ticket_type" />

          <van-field v-model="form.component_warranty" label="部件保修到期日" readonly label-width="120px"
            v-if="!form.ticket_type" />

          <van-field v-model="form.ticket_title" label="标题" placeholder="请输入标题"
            :rules="[{ required: true, message: '标题不能为空' }]" required label-width="120px" />

          <van-field v-model="form.to_user_name" label="TO" readonly label-width="120px" ref="titleInputRef" />

          <van-field v-model="form.cc_users_name" is-link label="CC" placeholder="点击选择抄送人" @click="ccShow = true"
            readonly label-width="120px" />

          <van-cell-group inset style="margin: 0;">
            <van-field v-model="form.ticket_desc" rows="2" autosize label="详细描述" type="textarea" maxlength="1000"
              placeholder="请输入" show-word-limit :rules="[{ required: true, message: '详细描述不能为空' }]" required
              label-width="120px" ref="descInputRef" />
          </van-cell-group>
        </van-cell-group>

        <van-field name="uploader" label="附件" style="padding-left: 35px;" v-if="!cieType">
          <template #input>
            <van-uploader :max-count="5"
              accept=".docx,.xlsx,.pptx,.txt,.pdf,.jpg,.png,.zip,.xls,.xlsm,.doc,.docm,.ppt,.pptm,.pps"
              :after-read="afterRead">
              <div class="work-uploader">上传...</div>
            </van-uploader>
          </template>
        </van-field>

        <!-- <div v-if="!cieType"> -->
        <template v-for="item in form.attachment" :key="item.file_path">
          <div class="work-file">
            <div class="work-file-name" @click="previewFile(item)">
              <u>{{ item.file_name }}</u>
            </div>
            <div @click="deleteFile(item.file_path)">
              <van-icon name="cross" />
            </div>
          </div>
        </template>
        <!-- </div> -->

        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" color="#bf1920">
            提交
          </van-button>
        </div>

        <!-- Safari底部空间|Edge底部空间 - 确保提交按钮下方有足够空间 -->
        <div :class="[
          isSafariBrowserValue
            ? 'safari-bottom-space'
            : isAndroidEdgeBrowserValue
              ? 'edge-bottom-space'
              : '',
        ]" v-if="isSafariBrowserValue || isAndroidEdgeBrowserValue"></div>
      </van-form>
    </div>

    <!-- 全文检索 -->
    <van-popup v-model:show="addShow" position="bottom" :style="{ height: '100%' }">
      <van-watermark :content="store.AppState.userName" text-color="rgba(0, 0, 0, .1)" :gap-x="80" :gap-y="10" />

      <van-nav-bar title="检索结果" left-text="返回" left-arrow @click-left="addShow = false" />
      <div class="title-content-name">
        下面是与您填写问题相关的信息，请参考并尝试解决问题。如果问题仍无法解决，请点击提交。
      </div>

      <div class="view-content">
        <!-- 搜索内容 -->
        <retrieval ref="viewRef" />
      </div>

      <van-button round block type="primary" color="#bf1920" class="submit-button" @click="viewSubmitForm">
        提交
      </van-button>

    </van-popup>

    <!-- 通讯录 -->
    <contactsPopUp v-model="ccShow" parameter="cc" operate_type="create" :customer_id="form.customer_id"
      :commonly-list-id="form.cc_users" @checkboxChange="checkboxChange" />
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/user'
import { download } from '@/utils/downloadUrl'
import { useRoute, useRouter } from 'vue-router'
import retrieval from '@/components/Retrieval.vue'
import contactsPopUp from '@/components/ContactsPopUp.vue'
import { isSafariBrowser, isEdgeBrowser } from '@/utils/browser'
import { AddFormType, CommonlyType } from '@/api/worksheets/type'
import {
  getClient,
  getContactPhone,
  getDeviceNumber,
  getFabList,
  getFrom,
  workAttachmentDownload,
  workAttachmentUpload,
  workClassify,
  workDeviceNumber,
} from '@/api/worksheets'
import { ref, computed, onMounted } from 'vue'
import useKeyboard from '@/utils/keyboard'

const { hideKeyboard } = useKeyboard()

const cieType = computed(() => {
  return Number(localStorage.getItem('mobile_userType'))
})

// 检测是否是Safari浏览器
const isSafariBrowserValue = ref(false)

// 检测是否是安卓Edge浏览器
const isAndroidEdgeBrowserValue = ref(false)

onMounted(() => {
  isSafariBrowserValue.value = isSafariBrowser()
  isAndroidEdgeBrowserValue.value =
    isEdgeBrowser().isEdge && isEdgeBrowser().isAndroid
})

const resetForm = (): AddFormType => {
  return {
    created_by: null, //工单创建人id
    created_by_name: '', //工单创建人名称
    supervisor: null, //负责人
    supervisor_name: '', //负责人名称
    customer: '', // FAB名称
    customer_id: null, // FABid,
    reporter: null, // 客户联系人id
    reporter_name: '', // 客户联系人名称
    phone_number: '', //电话
    email_address: '', //邮箱
    ticket_type_name: '', //工单类型id
    ticket_type: null, //工单类型id
    ticket_cate_name: '', //工单分类名称
    ticket_cate: null, //工单分类
    device_sn_cust: '', //客户设备编号
    device_sn_cust_name: '', //客户设备编号名称
    device_status_name: '', //设备名称
    device_status: '', //设备状态
    device_type: '', //设备型号
    device_sn: '', //设备序列号
    device_warranty: '', //备保修日
    component_warranty: '', //部件保修日
    ticket_title: route.query.title
      ? (route.query.title as string).substring(0, 120)
      : '', //标题
    to_user: null, //TO
    to_user_name: '', //TO名称
    cc_users_name: '', //CC选中名称
    cc_users: [], //CC选中id
    ticket_desc: '', //详细描述
    attachment: [], //附件
  }
}
const route = useRoute()

const router = useRouter()

const store = useUserStore()

const form = ref(resetForm())

const fabShow = ref(false)

const clientShow = ref(false)

const workTypeShow = ref(false)

const classifyShow = ref(false)

const deviceNumberShow = ref(false)

const deviceStatusShow = ref(false)

const ccShow = ref(false)

const ticketFullText = ref(false)

const addShow = ref(false)

const fabColumns = ref([])

const clientColumns = ref([])

const deviceNumberColumns = ref<CommonlyType[]>([])

const fabValue = ref([])

const clientValue = ref([])

const deviceNumberValue = ref([])

const viewRef = ref<InstanceType<typeof retrieval>>()

const titleInputRef = ref<HTMLInputElement | HTMLTextAreaElement | null>(null)

const descInputRef = ref<HTMLInputElement | HTMLTextAreaElement | null>(null)

const customFieldName = {
  text: 'name',
  value: 'id',
}

const uploadType = [
  '.docx',
  '.xlsx',
  '.pptx',
  '.txt',
  '.pdf',
  '.jpg',
  '.png',
  '.zip',
  '.xls',
  '.xlsm',
  '.doc',
  '.docm',
  '.ppt',
  '.pptm',
  '.pps',
]

//工单类型
const workOrderActions1 = [
  { text: '问题', value: 0 },
  { text: '咨询&要求', value: 1 },
]

//工单分类/问题
const issueClassify = ref([
  {
    text: '故障维修',
    value: 0,
  },
  {
    text: '精度',
    value: 1,
  },
  {
    text: '产品咨询',
    value: 2,
  },
])

//工单分类/咨询&要求
const consultationClassify = ref([
  {
    text: '视频',
    value: 3,
  },
  {
    text: '资料',
    value: 4,
  },
  {
    text: '部件',
    value: 5,
  },
])

//设备状态
const equipmentActions = ref([
  {
    text: '设备可以运行',
    value: '0',
  },
  {
    text: '设备无法运行',
    value: '1',
  },
])

//获取客户详情
const getClientInformation = async () => {
  try {
    const res: any = await getClient()

    fabColumns.value = res.customer_list

    Object.assign(form.value, res.user_info)

    form.value.created_by = res.user_info?.created_by?.id

    form.value.created_by_name = res.user_info?.created_by?.name

    form.value.reporter = res.user_info?.reporter?.id

    form.value.reporter_name = res.user_info?.reporter?.name

    form.value.customer_id = res.user_info?.customer?.id

    form.value.customer = res.user_info?.customer?.name

    // personId.value = res.user_info.id

    ticketFullText.value = res.new_ticket_fulltext_on

    if (form.value.customer_id) {
      deviceSnChange(form.value.customer_id)
    }
  } catch (err) {
    //
  }
}

getClientInformation()

//FAB选择
const fabOnConfirm = ({ selectedValues, selectedOptions }) => {
  form.value.customer = selectedOptions[0]?.name
  form.value.customer_id = selectedOptions[0]?.id
  fabValue.value = selectedValues
  fabShow.value = false

  contact(selectedOptions[0]?.id)

  deviceSnChange(selectedOptions[0]?.id)
}

//客户联系人选择
const clientOnConfirm = ({ selectedValues, selectedOptions }) => {
  form.value.reporter_name = selectedOptions[0]?.name
  form.value.reporter = selectedOptions[0]?.id
  clientValue.value = selectedValues
  clientShow.value = false

  reporterChange(selectedOptions[0]?.id)
}

//点击设备编号
const deviceNumber = () => {
  if (form.value.customer) {
    deviceNumberShow.value = true
  } else {
    deviceNumberShow.value = false
  }
}

//客户设备编号选择
const customFieldConfirm = ({ selectedValues, selectedOptions }) => {
  form.value.device_sn_cust_name = selectedOptions[0]?.name
  form.value.device_sn_cust = selectedOptions[0]?.id
  deviceNumberValue.value = selectedValues
  deviceNumberShow.value = false

  numberSnChange(selectedOptions[0]?.id)
}

//通过FAB获取客户联系人
const contact = async (val: number) => {
  try {
    const res: any = await getFabList({ customer_id: val })

    clientColumns.value = res.data || []
  } catch (err) {
    //
  }
}

//通过FAB获取客户设备编号
const deviceSnChange = async (val: number) => {
  try {
    const res: any = await workDeviceNumber({ customer_id: val })

    deviceNumberColumns.value = res.device_list || []
  } catch (err) {
    //
  }
}

//选择工单类型
const onSelect = (val: { text: string; value: number }) => {
  form.value.ticket_type_name = val.text

  form.value.ticket_type = val.value
}

//选择工单分类
const classifyOnSelect = (val: { text: string; value: number }) => {
  form.value.ticket_cate_name = val.text

  form.value.ticket_cate = val.value

  workTypeChange(val.value)
}

//选择设备状态
const deviceSelect = (val: { text: string; value: string }) => {
  form.value.device_status_name = val.text

  form.value.device_status = val.value
}

//工单分类获取负责人和To
const workTypeChange = async (val: number) => {
  const params = {
    customer: form.value.customer_id,
    ticket_type: form.value.ticket_type,
    ticket_cate: val,
  }

  try {
    const res: any = await workClassify(params)

    form.value.supervisor = res.data.id || null

    form.value.supervisor_name = res.data.name || ''

    form.value.to_user = res.data.id || null

    form.value.to_user_name = res.data.name || ''
  } catch (err) {
    //
  }
}

//通过客户联系人获取电话和邮箱
const reporterChange = async (val: number) => {
  try {
    const res: any = await getContactPhone({ id: val })

    form.value.phone_number = res.phone_number

    form.value.email_address = res.email_address
  } catch (err) {
    //
  }
}

//通过客户设备编号获取对应数据
const numberSnChange = async (val: number) => {
  try {
    const res: any = await getDeviceNumber({ device_sn_cust: val })

    form.value.device_type = res.data.device_type

    form.value.device_sn = res.data.device_sn

    form.value.device_warranty = res.data.device_warranty

    form.value.component_warranty = res.data.component_warranty
  } catch (err) {
    //
  }
}

// 文件上传
const afterRead = async (uploadFile: any) => {
  if (form.value.attachment.length >= 5) {
    showFailToast('最多上传5个文件')
    return
  }

  //  文件大小不能超过 10MB
  const isLt2M = uploadFile.file.size
    ? uploadFile.file.size / 1024 / 1024 <= 10
    : true

  //上传文件是否包含.
  const Suffix = uploadFile.file.name.includes('.')

  //取文件后缀
  const fileSuffix = uploadFile.file.name
    .split('.')
  [uploadFile.file.name.split('.').length - 1].toLowerCase()

  // 不支持上传的文件类型
  const notSupportedType = uploadType.includes('.' + fileSuffix)

  if (!isLt2M) {
    showFailToast('上传文件大小不能超过 10MB!')
    return
  } else if (!notSupportedType || !Suffix) {
    showFailToast('不支持上传该文件类型')
    return
  }

  const nativeFile: File = (uploadFile.file as unknown) as File

  const res: any = await workAttachmentUpload({
    file_name: nativeFile.name,
    type: nativeFile.type,
  })

  const params = {
    uid: nativeFile.lastModified,
    file_name: nativeFile.name,
    file_path: res.file_path,
  }

  form.value.attachment.push(params)

  const xhr = new XMLHttpRequest()

  xhr.open('PUT', res.upload_url, true)

  xhr.setRequestHeader('Content-Type', nativeFile?.type as string)

  xhr.send(nativeFile)
}

//删除附件
const deleteFile = (path: string) => {
  form.value.attachment = form.value.attachment.filter(
    (item: any) => item.file_path !== path,
  )
}

//附件下载
const previewFile = async (items: any) => {
  const file: any = form.value.attachment.find(
    (item: any) => item.uid === items.uid,
  )

  const params = {
    file_path: file.file_path,
    file_name: file.file_name,
  }

  const res: any = await workAttachmentDownload({ file_path: params.file_path })

  download(res.download_url, params.file_name)
}

//获取cc数据
const checkboxChange = async (val: CommonlyType[]) => {
  form.value.cc_users = val.map((item: CommonlyType) => item.id)

  form.value.cc_users_name = val
    .map((item: CommonlyType) => item.name)
    .join(',')
}

// form提交
const formView = async () => {
  try {
    const res: any = await getFrom(form.value)

    if (res.statusCode == 200) {
      addShow.value = false

      form.value = resetForm()

      showSuccessToast(res.message)

      await router.push('/menu/worksheets')
    }
  } catch (error) {
    //
  }
}

//新增提交
const submit = async () => {
  if (ticketFullText.value) {
    addShow.value = true

    nextTick(() => {
      viewRef.value?.searchView(form.value.ticket_title, false)
    })

    return
  }

  await formView()

  clearForm()
}

//弹窗提交
const viewSubmitForm = async () => {
  addShow.value = false

  await formView()

  router.push('/menu/worksheets')

  clearForm()
}

// 返回上一级
const onClickLeft = () => {
  router.go(-1)

  clearForm()
}

//重置表单
const clearForm = () => {
  form.value = resetForm()

  fabValue.value = []

  clientValue.value = []

  deviceNumberValue.value = []
}

// 页面滚动时关闭键盘
const handleTouchMove = () => {
  hideKeyboard()
}
</script>

<style lang="scss" scoped>
.work-order {
  width: 100%;
  height: 100vh;

  .work-order-content {
    height: calc(100vh - 40px);
    overflow-y: auto;
    // padding-bottom: env(safe-area-inset-bottom, 0); /* 使用iOS安全区域变量 */
    overscroll-behavior: contain;
    /* 防止过度滚动 */
  }

  /* Safari底部空间样式 */
  .safari-bottom-space {
    height: 80px;
    /* 增加高度以确保足够空间 */
    width: 100%;
  }

  /* Edge底部空间样式 */
  .edge-bottom-space {
    height: 170px;
    /* 为Edge浏览器提供更多底部空间 */
    width: 100%;
  }

  .work-uploader {
    width: 60px;
    height: 25px;
    background: #d9d9d9;
    text-align: center;
    line-height: 25px;
    border-radius: 10px;
    font-size: 12px;
    font-weight: 600;
    margin-top: 2px;
  }

  .work-file {
    width: 100%;
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-top: 10px;
    padding-left: 140px;

    .work-file-name {
      width: 180px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color: #0349e7;
    }
  }

  .title-content-name {
    width: 95%;
    margin: 0 auto;
    font-size: 12px;
    color: #bf1920;
    font-weight: 600;
  }

  .view-content {
    height: calc(100vh - 120px);
    overflow-y: auto;
  }

  .submit-button {
    width: 95%;
    position: fixed;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
  }

  :deep(.van-form) {
    .van-cell-group {
      .van-cell {
        .van-field__label--required:before {
          margin-left: -7px;
        }
      }
    }
  }

  :deep(.van-nav-bar__title) {
    font-size: 15px;
  }
}
</style>

<style>
.work-order em {
  color: #bf1920 !important;
  font-style: normal;
}
</style>